/*
 * dmBridge: a data access framework for CONTENTdm(R)
 *
 * Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
 * Education, on behalf of the University of Nevada, Las Vegas
 */

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */

$(document).ready(function() {
	init();
});

function init() {
	$("#outputLink").parent().hide();
	$("#convert").click(function() {
		convert();
	});
}

function convert() {
	var uri = new URI($("#inputCQR").val());
	if (uri.validationErrors.length > 0) {
		alert(uri.validationErrors[0]);
		return;
	}

	uri.host = $("#host").val();

	uri.path = $("#dmBridgeRoot").val() + "/objects";
	
	if ($("#collection").val() != "/dmdefault") {
		uri.path += $("#collection").val();
	}

	var allowedKeys = ["CISOROOT", "CISOFIELD1", "CISOFIELD2", "CISOFIELD3",
		"CISOFIELD4", "CISOOP1", "CISOOP2", "CISOOP3", "CISOOP4", "CISOBOX1",
		"CISOBOX2", "CISOBOX3", "CISOBOX4"];
	for (var i = 0; i < uri.queryKeys.length; i++) {
		var key = uri.queryKeys[i];
		if (jQuery.inArray(key, allowedKeys) < 0) {
			uri.unsetQueryValuesForKey(key);
			i--;
		}
	}
	for (i = 1; i < 5; i++) {
		var fields = uri.getQueryValuesForKey("CISOFIELD" + i);
		var strings = uri.getQueryValuesForKey("CISOBOX" + i);
		var modes = uri.getQueryValuesForKey("CISOOP" + i);

		if ((fields.length > 0 && fields[0].length < 1)
				|| (strings.length > 0 && strings[0].length < 1)
			|| (modes.length > 0 && modes[0].length < 1)) {
			uri.unsetQueryValuesForKey("CISOFIELD" + i);
			uri.unsetQueryValuesForKey("CISOBOX" + i);
			uri.unsetQueryValuesForKey("CISOOP" + i);
		}
	}

	var str = uri.toAbsolutePath();

	$("#outputCQR").val(str);
	$("#outputLink").parent().show();
	$("#outputLink").attr("href", str);
}
